<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图片上传测试</title>
  <style>
    body { font-family: Arial, sans-serif; padding: 20px; }
    .preview { margin-top: 20px; }
    .preview img { max-width: 300px; max-height: 300px; display: block; margin-bottom: 10px; }
    .response { margin-top: 20px; word-break: break-all; }
  </style>
</head>
<body>
  <h1>图片上传测试</h1>
  <form id="uploadForm">
    <label for="fileInput">选择图片：</label>
    <input type="file" id="fileInput" name="file" accept="image/*" required />
    <br/><br/>
    <button type="submit">上传</button>
  </form>

  <div class="preview" id="preview"></div>
  <div class="response" id="response"></div>
  <div class="uploaded-image" id="uploadedImage"></div>

  <script>
    const form = document.getElementById('uploadForm');
    const fileInput = document.getElementById('fileInput');
    const preview = document.getElementById('preview');
    const responseDiv = document.getElementById('response');
    const uploadedImageDiv = document.getElementById('uploadedImage');

    fileInput.addEventListener('change', () => {
      preview.innerHTML = '';
      uploadedImageDiv.innerHTML = '';
      const file = fileInput.files[0];
      if (!file) return;
      const img = document.createElement('img');
      img.src = URL.createObjectURL(file);
      preview.appendChild(img);
    });

    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      responseDiv.textContent = '上传中...';
      uploadedImageDiv.innerHTML = '';

      const formData = new FormData();
      formData.append('file', fileInput.files[0]);

      try {
        const res = await fetch('http://localhost:8080/upload/image', {
          method: 'POST',
          body: formData
        });
        const data = await res.json();
        if (data.code === 0) {
          const url = data.data.url;
          responseDiv.innerHTML = `上传成功：<a href="${url}" target="_blank">${url}</a>`;
          const uploadedImg = document.createElement('img');
          uploadedImg.src = url;
          uploadedImg.alt = 'Uploaded Image';
          uploadedImageDiv.appendChild(uploadedImg);
        } else {
          responseDiv.textContent = `上传失败：${data.msg}`;
        }
      } catch (err) {
        responseDiv.textContent = '请求出错：' + err;
      }
    });
  </script>
</body>
</html>